package com.homwee.factory.pageData;

import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.homwee.factory.FactoryActivity;
import com.homwee.factory.R;
import com.homwee.factory.util.Contants;
import com.homwee.listMenu.util.MenuItemData;
//import com.changhong.tvos.common.exception.IllegalValueException;
import com.mediatek.twoworlds.factory.MtkTvFApiSystem;
import com.mediatek.twoworlds.factory.MtkTvFApiInformation;

public class PageData8 extends PageData{
	
	public PageData8(FactoryActivity mFactoryActivity){
		super(mFactoryActivity);
	}
	final String TAG="CHFactory.pageData8";
	List<MenuItemData> mSubList =new ArrayList<MenuItemData>();

	//Dynamic BackLight
	String[] picModeStep={"User","Sport","Vivid","Standard","Movie","Game","Energy_Saving"};
	String[] backLightStep={"Off","Low","Middle","High"};

	public int mCurPicMode=0;
	public int mCurBlEffect=0;

	HashMap<String, Integer > picModeMap  = new HashMap<String, Integer>(){{
		put("User",0);
		put("Sport",2);
		put("Vivid",3);
		put("Standard",7);
		put("Movie",9);
		put("Game",10);
		put("Energy_Saving",11);
	}};
	final String LOW_SHRINK="PWM1:SHRINK";
	final String MID_SHRINK="PWM2:SHRINK";
	final String HIGH_SHRINK="PWM3:SHRINK";
	final String WHITEOUT_WHITE="WHITE_OUT:WHITE";
	final String WHITE0UT_WHITE_BL="WHITE_OUT:WHITE_BL";
	final String STEPOUT_STEP_LOW="STEP_OUT:STEP_LOW";
	final String STEPOUT_STEP_MID="STEP_OUT:STEP_MID";
	final String STEPOUT_STEP_MAX="STEP_OUT:STEP_MAX";
	final String SPEED_SPEED="SPEED_OUT:SPEED";
	final String BL_TIMES="BL_TIMES_OUT:BL_TIMES";

	MenuItemData mDynamicBackLight;
	MenuItemData mDyPicMode;
	MenuItemData mBLEffect;
	MenuItemData mShrink;
	MenuItemData mWhite;
	MenuItemData mWhiteBL;
	MenuItemData mStepLow;
	MenuItemData mStepMid;
	MenuItemData mStepMax;
	MenuItemData mSpeed;
	MenuItemData mBLTimes;
	MenuItemData mOutput;

	
	public List<MenuItemData> LoadPageData(){
		mListItemData.clear();
		mSubList.clear();

		mCurPicMode=getCurPicMode();
		mCurBlEffect=Settings.Global.getInt(mContext.getContentResolver(), getBlackLightName(getCurPicMode()), 0);

		String []backLightArray={"0","50","100"};
		String picModeValueStr="null";
		String picBacklightStr="null";
		String dreamTimeStr="null";
		Context context=this.mContext;
		String backLightStr = mFactoryActivity.getResources().getString(R.string.factory_backlight);
		String panelTestStr = mFactoryActivity.getResources().getString(R.string.factory_pageeight_panel_test);
		String picModeStr=mFactoryActivity.getResources().getString(R.string.factory_picture_mode);
		String dreamTime=mFactoryActivity.getResources().getString(R.string.factory_dream_time);
		MenuItemData backLight =new MenuItemData(0,backLightStr,0,2,2,backLightArray,1, MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		File mediaFile=new File(Contants.DEMOVIDEO_PATH);
		try {
			backLight.mInitValue= factorySetting.getBackLight()/50;
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		backLight.setOnValueChange(new MenuItemData.onValueChange() {
			
			public void valueChange(int value) {
				// TODO Auto-generated method stub
				Log.v("tv","setBackLight");
				try {
					factorySetting.setBackLight(value*50);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		MenuItemData mPanelTest =new MenuItemData(panelTestStr);
		mPanelTest.setOnEnterKey(new MenuItemData.onEnterRightKey() {
			@Override
			public void onEnterRightKey() {
				Intent tempIntent=new Intent(Intent.ACTION_VIEW);
				tempIntent.setComponent(new ComponentName("com.homwee.factory","com.homwee.factory.TestImagePatternsActivity"));
				mFactoryActivity.startActivity(tempIntent);
			}
		});

		MenuItemData mDimmingTest = new MenuItemData("Dimming Test");
		mDimmingTest.setOnEnterKey(new MenuItemData.onEnterRightKey() {
			@Override
			public void onEnterRightKey() {
				Intent tempIntent=new Intent(Intent.ACTION_VIEW);
				tempIntent.setComponent(new ComponentName("com.homwee.factory","com.homwee.factory.TestImagePatternsActivity"));
				tempIntent.putExtra("dimmingTest",1);
				mFactoryActivity.startActivity(tempIntent);
			}
		});
		
		try {
			picModeValueStr=Settings.Global.getInt(mContext.getContentResolver(), "picture_mode")+"";
			picBacklightStr=Settings.Global.getInt(mContext.getContentResolver(), "picture_backlight")+"";
			dreamTimeStr=Settings.System.getInt(mContext.getContentResolver(), SCREEN_OFF_TIMEOUT)+"";
		} catch (SettingNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		MenuItemData mPicMode  = new MenuItemData(picModeValueStr, picModeStr,picModeValueStr,
				MenuItemData.EN_ItemType.EN_OPTIONTEXTVIEW);
		MenuItemData mPicBacklight=new MenuItemData(picBacklightStr, 
				mFactoryActivity.getResources().getString(R.string.factory_backlight_in_setting)
				,picBacklightStr,MenuItemData.EN_ItemType.EN_OPTIONTEXTVIEW);
		MenuItemData mDreamTime=new MenuItemData(dreamTimeStr, dreamTime,dreamTimeStr,
				MenuItemData.EN_ItemType.EN_OPTIONTEXTVIEW);

		MenuItemData copyVideo=new MenuItemData("copyVideo");
		copyVideo.setOnEnterKey(new MenuItemData.onEnterRightKey() {
			@Override
			public void onEnterRightKey() {
				// TEST CODE
				String path="";
				if(factorySetting.findUsbDir()) {
					File mediaFile = factorySetting.getFile("demoVideo.mp4");
					if (mediaFile.exists()) {
						path = mediaFile.getAbsolutePath();
						factorySetting.copyVideoFile(path,"/sdcard/Movies/");
						Toast.makeText(mContext,"success",Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(mContext,"video not found",Toast.LENGTH_LONG).show();
					}
				} else {
					Toast.makeText(mContext,"video not found",Toast.LENGTH_LONG).show();
				}
			}
		});

		String playDemoVideo="Play Demo Video";
		MenuItemData mplayDemoVideo=new MenuItemData(0,playDemoVideo,0,1,0,mFactoryActivity.getResources().getStringArray(R.array.factoryCloseOrOpen),1, MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		mplayDemoVideo.mInitValue=Integer.parseInt(factorySetting.getShowModePlay());
		mplayDemoVideo.setOnValueChange(new MenuItemData.onValueChange() {
			@Override
			public void valueChange(int value) {
				factorySetting.setShowModePlay(Integer.toString(value));
				if(mediaFile.exists()){
					if(value==1){
						factorySetting.playDemoVideo(Contants.DEMOVIDEO_PATH,context);
					}
				}else{
					Toast.makeText(mContext,"Demo Video not exists",Toast.LENGTH_LONG).show();
				}
			}
		});

		//dynamic backlight

		//dynamic backlight init value
		String mShrinkInitVal=MtkTvFApiInformation.getInstance().
				getIniParameter(Contants.PATH_FACTORYINI,getShrinkName(mCurBlEffect));
		String mWhiteInitVal=MtkTvFApiInformation.getInstance().
				getIniParameter(Contants.PATH_FACTORYINI,WHITEOUT_WHITE);
		String mWhiteBLInitVal=MtkTvFApiInformation.getInstance().
				getIniParameter(Contants.PATH_FACTORYINI,WHITE0UT_WHITE_BL);
		String mStepLowInitVal=MtkTvFApiInformation.getInstance().
				getIniParameter(Contants.PATH_FACTORYINI,STEPOUT_STEP_LOW);
		String mStepMidInitVal=MtkTvFApiInformation.getInstance().
				getIniParameter(Contants.PATH_FACTORYINI,STEPOUT_STEP_MID);
		String mStepMaxInitVal=MtkTvFApiInformation.getInstance().
				getIniParameter(Contants.PATH_FACTORYINI,STEPOUT_STEP_MAX);
		String mSpeedInitVal=MtkTvFApiInformation.getInstance().
				getIniParameter(Contants.PATH_FACTORYINI,SPEED_SPEED);
		String mBLTimesInitVal=MtkTvFApiInformation.getInstance().
				getIniParameter(Contants.PATH_FACTORYINI,BL_TIMES);
		Log.d(TAG,"dynamic backlight init value:"+mShrinkInitVal+"|"+mWhiteInitVal+"|"+mWhiteBLInitVal+"|"+mStepLowInitVal+"|"+mStepMidInitVal+"|"+mStepMaxInitVal+"|"+
				mSpeedInitVal+"|"+mBLTimesInitVal);

		int mShrinkInit=0;
		int mWhiteInit=0;
		int mWhiteBLInit=0;
		int mStepLowInit=0;
		int mStepMidInit=0;
		int mStepMaxInit=0;
		int mSpeedInit=0;
		int mBLTimesInit=0;
		try{
			mShrinkInit=Integer.parseInt(mShrinkInitVal);
			mWhiteInit=Integer.parseInt(mWhiteInitVal);
			mWhiteBLInit=Integer.parseInt(mWhiteBLInitVal);
			mStepLowInit=Integer.parseInt(mStepLowInitVal);
			mStepMidInit=Integer.parseInt(mStepMidInitVal);
			mStepMaxInit=Integer.parseInt(mStepMaxInitVal);
			mSpeedInit=Integer.parseInt(mSpeedInitVal);
			mBLTimesInit=Integer.parseInt(mBLTimesInitVal);
		}catch (NumberFormatException exception){
			Log.e(TAG,"catch NumberFormatException");

		}

		mDynamicBackLight=new MenuItemData("Dynamic BackLight");

		int mDyPicModeInit=findIndex(picModeStep,getKeyByValue(picModeMap,mCurPicMode));
		mDyPicMode=new MenuItemData(0,"Picture Mode",
				0,picModeStep.length-1,mDyPicModeInit,picModeStep,1,MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		mDyPicMode.setOnValueChange(new MenuItemData.onValueChange() {
			@Override
			public void valueChange(int value) {
				Settings.Global.putInt(context.getContentResolver(), "picture_mode",picModeMap.get(picModeStep[value]));
				mCurPicMode=picModeMap.get(picModeStep[value]);
				mCurBlEffect=Settings.Global.getInt(mContext.getContentResolver(), getBlackLightName(getCurPicMode()), 0);
				mBLEffect.updateValue(mCurBlEffect);

				String mShrinkInitVal=MtkTvFApiInformation.getInstance().
						getIniParameter(Contants.PATH_FACTORYINI,getShrinkName(mCurBlEffect));
				int mShrinkInit=0;
				try {
					mShrinkInit=Integer.parseInt(mShrinkInitVal);
				}catch (NumberFormatException exception){
					Log.e(TAG,"NumberFormatException in mBLEffect.setOnValueChange");
				}
				mShrink.updateValue(mShrinkInit);
			}
		});

		mBLEffect=new MenuItemData(0,"Level",
				0,backLightStep.length-1,mCurBlEffect,backLightStep,1,MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		mBLEffect.setOnValueChange(new MenuItemData.onValueChange() {
			@Override
			public void valueChange(int value) {
				Settings.Global.putInt(context.getContentResolver(),getBlackLightName(getCurPicMode()),value);
				mCurBlEffect=value;

				String mShrinkInitVal=MtkTvFApiInformation.getInstance().
						getIniParameter(Contants.PATH_FACTORYINI,getShrinkName(mCurBlEffect));
				int mShrinkInit=0;
				try {
					mShrinkInit=Integer.parseInt(mShrinkInitVal);
				}catch (NumberFormatException exception){
					Log.e(TAG,"NumberFormatException in mBLEffect.setOnValueChange");
				}
				mShrink.updateValue(mShrinkInit);
			}
		});


		mShrink=new MenuItemData(0,"Shrink",0,100,mShrinkInit,1, MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		mShrink.setOnValueChange(new MenuItemData.onValueChange() {
			@Override
			public void valueChange(int value) {
				MtkTvFApiInformation.getInstance().setIniParameter(Contants.PATH_FACTORYINI,getShrinkName(mCurBlEffect),value+"");
			}
		});


		mWhite=new MenuItemData(0,"White",0,255,mWhiteInit,1, MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		mWhite.setOnValueChange(new MenuItemData.onValueChange() {
			@Override
			public void valueChange(int value) {
				MtkTvFApiInformation.getInstance().setIniParameter(Contants.PATH_FACTORYINI,WHITEOUT_WHITE,value+"");
			}
		});


		mWhiteBL=new MenuItemData(0,"White BL",0,100,mWhiteBLInit,1, MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		mWhiteBL.setOnValueChange(new MenuItemData.onValueChange() {
			@Override
			public void valueChange(int value) {
				MtkTvFApiInformation.getInstance().setIniParameter(Contants.PATH_FACTORYINI,WHITE0UT_WHITE_BL,value+"");
			}
		});


		mStepLow=new MenuItemData(0,"Step Low",1,10,mStepLowInit,1, MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		mStepLow.setOnValueChange(new MenuItemData.onValueChange() {
			@Override
			public void valueChange(int value) {
				MtkTvFApiInformation.getInstance().setIniParameter(Contants.PATH_FACTORYINI,STEPOUT_STEP_LOW,value+"");
			}
		});


		mStepMid=new MenuItemData(0,"Step Mid",1,10,mStepMidInit,1, MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		mStepMid.setOnValueChange(new MenuItemData.onValueChange() {
			@Override
			public void valueChange(int value) {
				MtkTvFApiInformation.getInstance().setIniParameter(Contants.PATH_FACTORYINI,STEPOUT_STEP_MID,value+"");
			}
		});


		mStepMax=new MenuItemData(0,"Step Max",1,10,mStepMaxInit,1, MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		mStepMax.setOnValueChange(new MenuItemData.onValueChange() {
			@Override
			public void valueChange(int value) {
				MtkTvFApiInformation.getInstance().setIniParameter(Contants.PATH_FACTORYINI,STEPOUT_STEP_MAX,value+"");
			}
		});


		mSpeed=new MenuItemData(" ","Speed(ms)",mSpeedInitVal, MenuItemData.EN_ItemType.EN_OPTIONTEXTVIEW);
		mSpeed.setOnEnterKey(new MenuItemData.onEnterRightKey() {
			@Override
			public void onEnterRightKey() {
				final EditText et = new EditText(mContext);
				et.setInputType(InputType.TYPE_CLASS_NUMBER);
				new AlertDialog.Builder(mContext).setTitle("Set backlight refresh frequency interval")
						.setView(et)
						.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialogInterface, int i) {
								String value=et.getText().toString();
								MtkTvFApiInformation.getInstance().setIniParameter(Contants.PATH_FACTORYINI,SPEED_SPEED,value+"");
								mSpeed.updateValue(value);
							}
						}).setNegativeButton("Cancel",null).show();
			}
		});


		mBLTimes=new MenuItemData(0,"BL Times",1,100,mBLTimesInit,1, MenuItemData.EN_ItemType.EN_OPTIONVIEW);
		mBLTimes.setOnValueChange(new MenuItemData.onValueChange() {
			@Override
			public void valueChange(int value) {
				MtkTvFApiInformation.getInstance().setIniParameter(Contants.PATH_FACTORYINI,BL_TIMES,value+"");
			}
		});

		mOutput=new MenuItemData(" ","OutPut File","", MenuItemData.EN_ItemType.EN_OPTIONTEXTVIEW);
		mOutput.setOnEnterKey(new MenuItemData.onEnterRightKey() {
			@Override
			public void onEnterRightKey() {
				{
					// TEST CODE
					String path="";
					if(factorySetting.findUsbDir()) {
						File desFile = factorySetting.getFile("Download");
						if (desFile.exists()) {
							Toast.makeText(mContext, "start output factory.ini", Toast.LENGTH_LONG).show();
							path = desFile.getAbsolutePath();
							factorySetting.copyVideoFile(Contants.PATH_FACTORYINI,path);

							Handler handler = new Handler();
							handler.postDelayed(new Runnable() {
								@Override
								public void run() {
									Toast.makeText(mContext, "success output to Download Dir", Toast.LENGTH_LONG).show();
								}
							}, 10000);
						} else {
							Toast.makeText(mContext,"can not found Download Dir in USB",Toast.LENGTH_LONG).show();
						}
					} else {
						Toast.makeText(mContext,"USB not found",Toast.LENGTH_LONG).show();
					}
				}

			}
		});

		mSubList.add(mDyPicMode);
		mSubList.add(mBLEffect);
		mSubList.add(mShrink);
		mSubList.add(mWhite);
		mSubList.add(mWhiteBL);
		mSubList.add(mStepLow);
		mSubList.add(mStepMid);
		mSubList.add(mStepMax);
		mSubList.add(mSpeed);
		mSubList.add(mBLTimes);
		mSubList.add(mOutput);

		mDyPicMode.mParentGroup=mListItemData;
		mDyPicMode.mParent=mDynamicBackLight;
		mDynamicBackLight.mSubChildGroup=mSubList;

		mListItemData.add(backLight);
		mListItemData.add(mDynamicBackLight);
		mListItemData.add(mPanelTest);
		mListItemData.add(mDimmingTest);
		mListItemData.add(mPicMode);
		mListItemData.add(mPicBacklight);
		mListItemData.add(mDreamTime);
		mListItemData.add(copyVideo);
		mListItemData.add(mplayDemoVideo);



		return mListItemData;
	}

	private String getBlackLightName(int pictureMode){
		String autoBackName;
		switch (pictureMode){
			case 0:
				autoBackName="key_picture_mode_user_auto_backlight";
				break;
			case 2:
				autoBackName="key_picture_mode_sport_auto_backlight";
				break;
			case 3:
				autoBackName="key_picture_mode_vivid_auto_backlight";
				break;
			case 7:
				autoBackName="key_picture_mode_standard_auto_backlight";
				break;
			case 9:
				autoBackName="key_picture_mode_movie_auto_backlight";
				break;
			case 10:
				autoBackName="key_picture_mode_game_auto_backlight";
				break;
			case 11:
				autoBackName="key_picture_mode_energy_saving_auto_backlight";
				break;
			default:
				autoBackName="key_picture_mode_others_auto_backlight";
				break;
		}
		return autoBackName;
	}

	private int getCurPicMode(){
		return Settings.Global.getInt(mContext.getContentResolver(), "picture_mode",0);
	}

	private String getShrinkName(int BLEffect){
		switch(BLEffect){
			case 1:
				return LOW_SHRINK;
			case 2:
				return MID_SHRINK;
			case 3:
				return HIGH_SHRINK;
			default:
				Log.d(TAG,"in getShrinkName,back light effect input error");
				return "error";
		}
	}

	private String getKeyByValue(Map<String, Integer> map, Integer value) {
		for (Map.Entry<String, Integer> entry : map.entrySet()) {
			if (entry.getValue().equals(value)) {
				return entry.getKey();
			}
		}
		return null;
	}

	private int findIndex(String[] arr, String target) {
		for (int i = 0; i < arr.length; i++) {
			if (arr[i].equals(target)) {
				return i;
			}
		}
		return 0;
	}

}
